import { dislikeCommentAPI, likeCommentAPI, submitCommentAPI } from '@/api/comment';
import { getCommentsByIdAPI } from '@/api/detail';
import { AppDispatch } from '..';
import { CommentType } from '../reducer/comment';

export const saveOriginCommentAction = (commentData: CommentType) => {
  return {
    type: 'comment/saveOrigiComment',
    payload: commentData,
  };
};

export const clearOriginCommentAction = () => {
  return {
    type: 'comment/clearOrigiComment',
  };
};

export const submitCommentAction = (target: string, content: string, art_id?: string) => {
  return async (dispatch: AppDispatch) => {
    await submitCommentAPI({ target, content, art_id });
  };
};

export const getReplyCommentsByIdAction = (com_id: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getCommentsByIdAPI({ type: 'c', source: com_id });
    dispatch({ type: 'comment/saveReplyList', payload: res.data });
  };
};

export const clearReplyCommentsAction = () => {
  return {
    type: 'comment/saveReplyList',
    payload: {
      end_id: '',
      last_id: '',
      results: [],
      total_count: 0,
    },
  };
};

export const likeCommentsAction = (id: string, isLiking: boolean) => {
  return async (dispach: AppDispatch) => {
    if (!isLiking) {
      await likeCommentAPI(id);
      dispach({ type: 'comment/updateCommentById', payload: id });
      return;
    }
    await dislikeCommentAPI(id);
    dispach({ type: 'comment/updateCommentById', payload: id });
  };
};

export const likeReplyCommentsAction = (id: string, isLiking: boolean) => {
  return async (dispach: AppDispatch) => {
    if (!isLiking) {
      await likeCommentAPI(id);
      dispach({ type: 'comment/updateReplyCommentById', payload: id });
      return;
    }
    await dislikeCommentAPI(id);
    dispach({ type: 'comment/updateReplyCommentById', payload: id });
  };
};

export const likeOriginCommentsAction = (id: string, isLiking: boolean) => {
  return async (dispatch: AppDispatch) => {
    if (!isLiking) {
      await likeCommentAPI(id);
      dispatch({ type: 'comment/updateOriginComment' });
      return;
    }
    await dislikeCommentAPI(id);
    dispatch({ type: 'comment/updateOriginComment' });
  };
};
